<?php

namespace app\shopapi\model;

use app\api\model\UserConsumeLog;
use think\Db;
use think\Loader;
use think\Model;
use traits\model\SoftDelete;


class ShopOrder extends Model
{
    use SoftDelete;



    // 表名
    protected $name = 'shop_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';



    // 订单待付款
    const ORDER_CREATE = 0;

    // 订单已支付
    //const ORDER_PAY = 1;

    // 订单待使用
    const ORDER_VERIFY = 2;

    // 订单已完成
    const ORDER_COMPLETE = 3;
    // 订单已关闭
    const ORDER_CLOSE = -1;
    /**
     * 基础订单状态(不同类型的订单可以不使用这些状态，但是不能冲突)
     * @var unknown
     */
    public $order_status = [
        self::ORDER_CREATE => [
            'status' => self::ORDER_CREATE,
            'name' => '待支付',
        ],
        self::ORDER_VERIFY => [
            'status' => self::ORDER_VERIFY,
            'name' => '待使用',
        ],
        self::ORDER_COMPLETE => [
            'status' => self::ORDER_COMPLETE,
            'name' => '已完成',
        ],
        self::ORDER_CLOSE => [
            'status' => self::ORDER_CLOSE,
            'name' => '已关闭',
        ],

    ];

    protected $append = [
        'pay_time_text',
        'createtime_text',
    ];

    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    //核销单信息
    public function verifyInfo($verify_code,$shop_id)
    {
        if (empty($verify_code))throw new \Exception('缺少参数核销码');
        $order_info = ShopOrder::where(['verify_code'=>$verify_code,'shop_id'=>$shop_id])->find();
        if (empty($order_info)){
            throw new \Exception('该团购订单不是该店铺订单');
        }
        return $order_info;
    }

    //核销
    public function verify($verify_code,$shop_id,$user_id)
    {
        Db::startTrans();
        try {
            if (empty($verify_code))throw new \Exception('缺少参数订单编号');
            $shop = Shop::get($shop_id);
            $order_info = ShopOrder::where(['verify_code'=>$verify_code,'shop_id'=>$shop_id])->find();
            if (empty($order_info)){
                throw new \Exception('该团购订单不是该店铺订单');
            }
            if ($order_info['is_verify']==1){
                throw new \Exception('该订单已核销');
            }
            $order_info->is_verify = 1;
            $order_info->verify_time = time();
            $order_info->verifier_id = $user_id;
            $order_info->setAttr('order_status',self::ORDER_COMPLETE);
            $order_info->order_status_name = $this->order_status[ self::ORDER_COMPLETE ][ "name" ];
            $res = $order_info->save();

            //商品增加核销数量
            ShopGoods::where(['goods_id'=>$order_info->goods_id])->setInc('verify_num',1);
            //发放消费记录的收益
            UserConsumeLog::sendCommission($order_info->order_no);

            //分账
            /*$pay_model = new \app\shopapi\model\lakala\Pay();
            $split_amount = $order_info->pay_price-$order_info->channel_fee;
            $out_request_no = date("YmdHis") . sprintf("%08d", $shop_id) . mt_rand(1000, 9999);
            $refund_res = $pay_model->orderComplete($order_info->lakala_order_no,$shop['member_no'],$out_request_no,$split_amount);
            if ($refund_res['code']==0){
                throw new \Exception($refund_res['msg']);
            }*/

            //增加商户账单
            $bills_model = new ShopBills();
            //$bills_model->add($order_info->user_id,$order_info->shop_id,$order_info->pay_price,$order_info->pay_type,$order_info->pay_time,0,$order_info->lakala_order_no,$order_info->channel_fee);
            $bills_model->add([
                'user_id'=>$order_info->user_id,
                'shop_id'=>$order_info->shop_id,
                'pay_price'=>$order_info->pay_price,
                'pay_type'=>$order_info->pay_type,
                'trans_oktime'=>$order_info->pay_time,
                'consume_type'=>2,
                'order_no'=>$order_info->lakala_order_no,
                'service_charge'=>$order_info->channel_fee,
                'worker_id'=>0,
                'remark'=>'',
                'collect_money_remark'=>'',
            ]);
            Db::commit();

            return $res;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }


    }
}